#!/bin/bash

# 参数检查
if [ "$#" -lt 5 ]; then
  echo "Usage: $0 <executable_path> <output_dir> <package_name> <version> <architecture> [description]"
  exit 1
fi

EXECUTABLE_PATH=$1
OUTPUT_DIR=$2
PACKAGE_NAME=$3
VERSION=$4
ARCHITECTURE=$5
DESCRIPTION=${6:-"Godot Game"}

# 进度报告函数
report_progress() {
  echo "[PROGRESS] $1"
}

# 创建临时构建目录
report_progress "Creating temporary build directory..."
BUILD_DIR=$(mktemp -d)
PKG_DIR="$BUILD_DIR/${PACKAGE_NAME}_${VERSION}_${ARCHITECTURE}"
mkdir -p "$PKG_DIR/DEBIAN"
mkdir -p "$PKG_DIR/usr/games"
mkdir -p "$PKG_DIR/usr/share/applications"

# 复制可执行文件
report_progress "Copying executable..."
cp "$EXECUTABLE_PATH" "$PKG_DIR/usr/games/$PACKAGE_NAME"
chmod 755 "$PKG_DIR/usr/games/$PACKAGE_NAME"

# 创建桌面文件
report_progress "Creating desktop entry..."
cat > "$PKG_DIR/usr/share/applications/${PACKAGE_NAME}.desktop" <<EOF
[Desktop Entry]
Name=$PACKAGE_NAME
Exec=/usr/games/$PACKAGE_NAME
Icon=/usr/share/pixmaps/$PACKAGE_NAME.png
Terminal=false
Type=Application
Categories=Game;
EOF

# 创建DEBIAN/control文件
report_progress "Creating control file..."
cat > "$PKG_DIR/DEBIAN/control" <<EOF
Package: $PACKAGE_NAME
Version: $VERSION
Architecture: $ARCHITECTURE
Multi-Arch: foreign
Maintainer: $(whoami)@$(hostname)
Description: $DESCRIPTION
Depends: libc6, libasound2, libpulse0, libx11-6, libxext6, libxrandr2, libgl1-mesa-glx
EOF

# 创建postinst脚本
report_progress "Creating post-install script..."
echo "#!/bin/sh" > "$PKG_DIR/DEBIAN/postinst"
echo "chmod 755 /usr/games/$PACKAGE_NAME" >> "$PKG_DIR/DEBIAN/postinst"
chmod 755 "$PKG_DIR/DEBIAN/postinst"

# 构建deb包
report_progress "Building DEB package..."
dpkg-deb --build --root-owner-group "$PKG_DIR"
mv "$BUILD_DIR/${PACKAGE_NAME}_${VERSION}_${ARCHITECTURE}.deb" "$OUTPUT_DIR"

# 清理
report_progress "Cleaning up..."
rm -rf "$BUILD_DIR"

report_progress "COMPLETE"
echo "DEB package created: $OUTPUT_DIR/${PACKAGE_NAME}_${VERSION}_${ARCHITECTURE}.deb"